package io.renren.modules.cp.controller;

import io.renren.modules.cp.config.WxCpConfiguration;
import lombok.AllArgsConstructor;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.bean.WxCpMessage;
import me.chanjar.weixin.cp.bean.WxCpMessageSendResult;
import me.chanjar.weixin.cp.bean.article.NewArticle;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * @Description: TODO
 * @author: zlm
 * @date: 2020年07月20日 5:37 下午
 */
@AllArgsConstructor
@RestController
@RequestMapping("/wx/cp/message/{agentId}")
public class WxMessageController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @PostMapping("/post/textcard")
    public WxCpMessageSendResult textcardCreate(@PathVariable Integer agentId, @RequestBody Map<String, String> data) throws WxErrorException {
        String toUser = data.get("toUser");
        String title = data.get("title");
        String description = data.get("description");
        String url = data.get("url");
        String btnTxt = data.get("btnTxt");
        if (StringUtils.isAnyBlank(toUser, title, description, url, btnTxt)) {
            throw new IllegalArgumentException("请求参数非法，请核实!");
        }

        final WxCpService wxCpService = WxCpConfiguration.getCpService(agentId);
        WxCpMessage message = WxCpMessage
            .TEXTCARD()
            .agentId(agentId) // 企业号应用ID
            .toUser(toUser)
            //.toParty("非必填，PartyID列表，多个接受者用‘|’分隔。当touser为@all时忽略本参数")
            //.toTag("非必填，TagID列表，多个接受者用‘|’分隔。当touser为@all时忽略本参数")
            .title(title)
            .description(description)
            .url(url)
            .btnTxt(btnTxt)
            .build();

        return wxCpService.messageSend(message);
    }

    @PostMapping("/post/markdown")
    public WxCpMessageSendResult markdownCreate(@PathVariable Integer agentId, @RequestBody Map<String, String> data) throws WxErrorException {
        String toUser = data.get("toUser");
        String content = data.get("content");
        if (StringUtils.isAnyBlank(toUser, content)) {
            throw new IllegalArgumentException("请求参数非法，请核实!");
        }

        final WxCpService wxCpService = WxCpConfiguration.getCpService(agentId);
        WxCpMessage message = WxCpMessage
                .MARKDOWN()
                .agentId(agentId) // 企业号应用ID
                .toUser(toUser)
                //.toParty("非必填，PartyID列表，多个接受者用‘|’分隔。当touser为@all时忽略本参数")
                //.toTag("非必填，TagID列表，多个接受者用‘|’分隔。当touser为@all时忽略本参数")
                .content(content)
                .build();

        return wxCpService.messageSend(message);
    }
}
